home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / machserver / tests / cond_rw / readwrite.c < prev   
Encoding:
C/C++ Source or Header  |  1991-05-06  |  1.5 KB  |  116 lines

  1. /* 
  2.  * Forks a child that simply echoes characters passed to it.  Can 
  3.  * either use busy waiting or a condition variable to wait on the 
  4.  * shared buffer.  Uses a condition variable if USE_CONDITION is 
  5.  * defined.
  6.  */
  7.  
  8. #include <cthreads.h>
  9. #include <stdio.h>
  10.  
  11. #ifdef USE_CONDITION
  12. struct condition cond;
  13. #endif
  14.  
  15.  
  16. struct mutex lock;
  17. int buf = 0;
  18.  
  19. any_t ChildProc();
  20. void pause();
  21. void notify();
  22.  
  23. main()
  24. {
  25.     cthread_t child;
  26.     int ch;
  27.  
  28.     cthread_init();
  29.     mutex_init(&lock);
  30. #ifdef USE_CONDITION
  31.     condition_init(&cond);
  32. #endif
  33.  
  34.     child = cthread_fork(ChildProc, (any_t)0);
  35.  
  36.     do {
  37.         ch = getchar();
  38.         if (ch == 0)
  39.             continue;
  40.         sendach(ch);
  41.     } while (ch != EOF);
  42.  
  43.     cthread_join(child);
  44.     exit(0);
  45. }
  46.  
  47. any_t
  48. ChildProc(arg)
  49.     any_t arg;
  50. {
  51.     int ch;
  52.  
  53.     /* Wire our C thread to a kernel thread, for gdb's sake. */
  54.     cthread_wire();
  55.  
  56.     while ((ch = getach()) != EOF) {
  57.         if (ch == 'D') {
  58.             abort();
  59.         }
  60.         putchar(ch);
  61.         fflush(stdout);
  62.     }
  63. }
  64.  
  65. /* Wait until buf is empty, then put char in and return. */
  66. sendach(ch)
  67.     int ch;
  68. {
  69.     mutex_lock(&lock);
  70.  
  71.     while (buf != 0)
  72.         pause();
  73.     buf = ch;
  74.     notify();
  75.  
  76.     mutex_unlock(&lock);
  77. }
  78.  
  79. /* Wait until buf is not empty, then remove char and return it. */
  80. int
  81. getach()
  82. {
  83.     int ch;
  84.  
  85.     mutex_lock(&lock);
  86.  
  87.     while (buf == 0)
  88.         pause();
  89.     ch = buf;
  90.     buf = 0;
  91.     notify();
  92.  
  93.     mutex_unlock(&lock);
  94.     return(ch);
  95. }
  96.  
  97. void
  98. pause()
  99. {
  100. #ifdef USE_CONDITION
  101.     condition_wait(&cond, &lock);
  102. #else /* USE_CONDITION */
  103.     mutex_unlock(&lock);
  104.     cthread_yield();
  105.     mutex_lock(&lock);
  106. #endif /* USE_CONDITION */
  107. }
  108.  
  109. void
  110. notify()
  111. {
  112. #ifdef USE_CONDITION
  113.     condition_signal(&cond);
  114. #endif
  115. }
  116.